<script setup lang="ts">
import {message} from 'ant-design-vue';
import {useForm, useModal, z} from '#/ui-kit';
import {componentKeys} from '#/router/routes';
import {useDictStore} from '#/stores';

import {createMenuInfo, findMenuListTree, updateMenuInfo} from '#/api/system/menu';

const emits = defineEmits(['close']);

const {getDictData} = useDictStore();

const [Modal, modalApi] = useModal({
  draggable: true,
  closeOnClickModal: false,
  destroyOnClose: true,
  onConfirm: function () {
    formApi.validateAndSubmitForm();
  },
  onBeforeClose: function () {
    modalApi.setState({confirmLoading: false})
    modalApi.setData({});
    formApi.resetForm();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      formApi.setValues(modalApi.getData(), false, false);
    }
  }
});

const [Form, formApi] = useForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
      allowClear: true,
    },
  },
  layout: 'horizontal',
  wrapperClass: 'grid grid-cols-6',
  showDefaultActions: false,
  schema: [
    {
      label: '菜单类型',
      fieldName: 'menuType',
      component: 'RadioGroup',
      componentProps: {
        options: [
          {label: '目录', value: 0},
          {label: '菜单', value: 1},
          {label: '按钮', value: 2},
        ],
      },
      defaultValue: 0,
      formItemClass: 'col-span-3',
    },
    {
      label: '组件类型',
      fieldName: 'componentType',
      component: 'RadioGroup',
      componentProps: {
        options: [
          {label: '组件', value: 0},
          {label: '内链', value: 1},
          {label: '外链', value: 2},
        ],
      },
      defaultValue: 0,
      dependencies: {
        disabled(values) {
          return values.menuType === 2;
        },
        triggerFields: ['menuType'],
      },
      formItemClass: 'col-span-3',
    },
    {
      label: '上级菜单',
      fieldName: 'parentId',
      component: 'ApiTreeSelect',
      componentProps: {
        api: findMenuListTree,
        showSearch: true,
        treeNodeFilterProp: 'title',
        fieldNames: {
          value: 'id',
          label: 'title',
          children: 'children',
        },
        placeholder: '请选择上级菜单',
      },
      dependencies: {
        show: ({parentId}) => {
          return parentId !== 0;
        },
        triggerFields: ['parentId'],
      },
      rules: z.number({required_error: '请选择上级菜单'})
          .refine((value) => value != modalApi?.getData()?.id,
              {message: '当前所选项无法为上级菜单'}),
      formItemClass: 'col-span-6',
    },
    {
      label: '菜单名称',
      fieldName: 'title',
      component: 'Input',
      componentProps: {placeholder: '请输入菜单名称'},
      rules: 'required',
      formItemClass: 'col-span-6',
    },
    {
      label: '图标',
      fieldName: 'icon',
      component: 'IconPicker',
      componentProps: {
        prefix: 'lucide',
        placeholder: '请选择图标',
      },
      dependencies: {
        disabled(values) {
          return values.menuType === 2;
        },
        triggerFields: ['menuType'],
      },
      formItemClass: 'col-span-3',
    },
    {
      label: '排序',
      fieldName: 'sort',
      component: 'InputNumber',
      componentProps: {placeholder: '请输入排序'},
      defaultValue: 0,
      rules: 'required',
      formItemClass: 'col-span-3',
    },
    {
      label: '路由名称',
      fieldName: 'name',
      component: 'Input',
      componentProps: {placeholder: '请输入路由名称'},
      dependencies: {
        disabled(values) {
          return values.menuType === 2;
        },
        rules(values) {
          return values.menuType === 2 ? '' : 'required';
        },
        triggerFields: ['menuType'],
      },
      formItemClass: 'col-span-6',
    },
    {
      label: '路由地址',
      fieldName: 'path',
      component: 'Input',
      componentProps: {placeholder: '请输入路由地址'},
      dependencies: {
        disabled(values) {
          return values.menuType === 2;
        },
        rules(values) {
          return values.menuType === 2 ? '' : 'required';
        },
        triggerFields: ['menuType'],
      },
      formItemClass: 'col-span-6',
    },
    {
      label: '组件路径',
      fieldName: 'component',
      component: 'AutoComplete',
      componentProps: {
        class: 'w-full',
        placeholder: '请输入组件路径',
        filterOption(input: string, option: { value: string }) {
          return option.value.toLowerCase().includes(input.toLowerCase());
        },
        options: componentKeys.map((v) => ({value: v})),
      },
      dependencies: {
        disabled({menuType, componentType}) {
          return menuType === 2 || componentType !== 0;
        },
        rules({menuType, componentType}) {
          return menuType == 0 || menuType === 2 || componentType != 0 ? '' : 'required';
        },
        triggerFields: ['menuType', 'componentType'],
      },
      formItemClass: 'col-span-6',
    },
    {
      label: '权限标识',
      fieldName: 'authority',
      component: 'Input',
      componentProps: {
        placeholder: '请输入权限标识',
      },
      dependencies: {
        rules({authority}) {
          return authority ? z.string().regex(/^$|^([^:*]+|\*):([^:*]+|\*):([^:*]+|\*)/,
              '权限标识不符合 *:*:* 规范') : '';
        },
        triggerFields: ['authority'],
      },
      formItemClass: 'col-span-6',
    },
    {
      label: '链接地址',
      fieldName: 'link',
      component: 'Input',
      componentProps: {placeholder: '请输入链接地址'},
      dependencies: {
        disabled({componentType, menuType}) {
          return componentType === 0 || menuType === 2;
        },
        rules({componentType, menuType}) {
          return componentType === 0 || menuType === 2 ? '' : 'required';
        },
        triggerFields: ['componentType', 'menuType'],
      },
      formItemClass: 'col-span-6',
    },
    {
      label: '显示状态',
      fieldName: 'hiddenStatus',
      component: 'RadioGroup',
      componentProps: {
        options: [
          {label: '否', value: 1},
          {label: '是', value: 0}
        ],
      },
      defaultValue: 0,
      dependencies: {
        disabled(values) {
          return values.menuType === 2;
        },
        triggerFields: ['menuType'],
      },
      formItemClass: 'col-span-2',
    },
    {
      label: '启用状态',
      fieldName: 'enableStatus',
      component: 'RadioGroup',
      componentProps: {
        options: getDictData('enable_status', true),
      },
      defaultValue: 1,
      formItemClass: 'col-span-2',
    },
    {
      label: '缓存状态',
      fieldName: 'cacheStatus',
      component: 'RadioGroup',
      componentProps: {
        options: [
          {label: '否', value: 0},
          {label: '是', value: 1},
        ],
      },
      defaultValue: 0,
      dependencies: {
        disabled(values) {
          return values.menuType === 2;
        },
        triggerFields: ['menuType'],
      },
      formItemClass: 'col-span-2',
    },
  ],
  handleSubmit: function (values) {
    modalApi.setState({confirmLoading: true});
    if (values?.id) {
      updateMenuInfo(values).then(() => {
        message.success('菜单信息更新成功');
        modalApi.close();

        emits('close');
      }).finally(() => {
        modalApi.setState({confirmLoading: false});
      });
    } else {
      createMenuInfo(values).then(() => {
        message.success('菜单信息新增成功');
        modalApi.close();

        emits('close');
      }).finally(() => {
        modalApi.setState({confirmLoading: false});
      });
    }
  },
});
</script>

<template>
  <Modal>
    <Form/>
  </Modal>
</template>